using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

using Microsoft.CSharp;

namespace Pronghorn.Core
{
	public class SkinCompiler : ISkinCompiler
	{
		private readonly ISkinParser _parser;
		private readonly ISkinLocator _skinLocator;
		public SkinCompiler(ISkinLocator skinLocator, ISkinParser parser)
		{
			_skinLocator = skinLocator;
			_parser = parser;
		}

		private string[] getViewDependencies()
		{
            return new []{""};
		}
		public Assembly Compile()
		{
			TextWriter source = new StringWriter();
		    startCode(source);
			_parser.Parse(source);
            endCode(source);
            var providerOptions = new Dictionary<string, string>();
            providerOptions.Add("CompilerVersion", "v3.5");
			var provider = new CSharpCodeProvider(providerOptions);

		    var parameters = new CompilerParameters();
		    parameters.ReferencedAssemblies.Add("System.dll");
		    parameters.ReferencedAssemblies.Add("Pronghorn.Core.dll");
            parameters.ReferencedAssemblies.Add("System.Web.Mvc.dll");
		    parameters.ReferencedAssemblies.Add("System.Core.dll");
		    parameters.GenerateExecutable = false;
            parameters.TempFiles = new TempFileCollection(".", true);
            parameters.WarningLevel = 3;
		    parameters.IncludeDebugInformation = false;
            
		    parameters.OutputAssembly = "outputView.dll";
		    parameters.GenerateInMemory = false;
			var compiler = provider.CompileAssemblyFromSource(parameters, source.ToString());
			return compiler.CompiledAssembly;
		}

        private static void startCode(TextWriter source)
	    {
            source.WriteLine(@"using System.Collections.Generic;
                                using System.IO;
                                using System.Linq;
                                using Pronghorn.Core;");
            source.WriteLine("namespace ProngHorn.View{");
            source.WriteLine("public class ViewNameHere : SkinBase {");

            source.WriteLine(
                @"public ViewNameHere(IProngHornSkinContext skinContext, ICollectionRenderer collectionRenderer, IFileLinkRenderer scriptRenderer, IFileLinkRenderer cssRenderer)
			: base(skinContext, collectionRenderer, scriptRenderer,cssRenderer){}");

            source.WriteLine("protected override void GenerateHtml(TextWriter writer){");
	    }

        private static void endCode(TextWriter source)
        {
            source.WriteLine("}");//End GenerateHtml method
            source.WriteLine("}");//Class
            source.WriteLine("}");//Namespace
        }
	}
}